package com.ws.shop.action.front;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaService;
import com.ws.shop.bean.MailConfig;
import com.ws.shop.bean.Page;
import com.ws.shop.common.CommonData;
import com.ws.shop.common.JCaptchaEngine;
import com.ws.shop.entity.Loginlog;
import com.ws.shop.entity.Member;
import com.ws.shop.entity.Sunpic;
import com.ws.shop.service.LetterService;
import com.ws.shop.service.MemberService;
import com.ws.shop.service.ParticipateService;
import com.ws.shop.service.PunchService;
import com.ws.shop.service.SmtpService;
import com.ws.shop.service.SunpicService;
import com.ws.shop.service.VerificationService;
import com.ws.shop.util.CommonUtil;
import com.ws.shop.util.DateUtil;
import com.ws.shop.util.RequestUtil;
import com.ws.shop.util.StringUtil;
import com.ws.shop.util.TemplateConfigUtil;

/**
 * 用户处理
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="/front/*")//请求目录
public class UserAction extends BaseFrontAction{
	
	private static Logger log = Logger.getLogger(UserAction.class);
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private PunchService punchService;
	@Autowired
	private SmtpService smtpService;
	@Autowired
	private SunpicService sunpicService;
	@Autowired
	ParticipateService participateService;
	@Autowired
	private LetterService letterService;
	@Autowired
	private VerificationService verificationService;
	//登陆页面
	@RequestMapping(value="signin.htm",method=RequestMethod.GET)//请求地址
    public String signin()
    {
    	return "signin";
    }
    
    //注册页面
	@RequestMapping(value="register.htm",method=RequestMethod.GET)//请求地址
    public String register(){
    	return "register";
    }
    
	//注册成功页面
	@RequestMapping(value="regok.htm",method=RequestMethod.GET)//请求地址
    public String regok(){
    	return "regok";
    }
	
    //保密协议
	@RequestMapping(value="privacy.htm",method=RequestMethod.GET)//请求地址
    public String privacy(){
    	return "privacy";
    }
    
    //使用条款
	@RequestMapping(value="agreement.htm",method=RequestMethod.GET)//请求地址
    public String agreement(){
    	return "agreement";
    }
    
    //验证码
	@RequestMapping(value="verify.htm",method=RequestMethod.GET)//请求地址
	public String verify(){
		return "verify";
	}
	
	//添加用户发送邮件
	@RequestMapping(value="addmember.htm",method=RequestMethod.GET)//请求地址
	public String addmember(HttpServletRequest request,HttpServletResponse response){
		String toMail = RequestUtil.getStringParameter(request, "mail", null);
		String code = RequestUtil.getStringParameter(request, "code", null); 
		if (this.checkVerify(request, code)){
			if (this.checkEmail(toMail)){
				int c = verificationService.getpwd(toMail, "verification", StringUtil.getNumRandomStr(16));
				if(c!=0){
					return this.ajaxJsonErrorMessage(response, "处理失败!");
				}
				String header = "邮箱验证确认信";
			     //选择模板
                Map<String,Object> data = new HashMap<String,Object>();
				boolean info = smtpService.sendMail(header, "templateFilePath", data, toMail);
				if (info){
					return this.ajaxJsonSuccessMessage(response, "发送成功!");
				}else{
					return this.ajaxJsonErrorMessage(response, "发送失败!");
				}
			}else {
				return this.ajaxJsonErrorMessage(response, "邮箱错误!");
			}
		}else {
			return this.ajaxJsonErrorMessage(response, "验证码错误!");
		}
	}
	
	//再次发送邮件
	@RequestMapping(value="resendmail.htm",method=RequestMethod.GET)//请求地址
	public String resendmail(HttpServletRequest request,HttpServletResponse response){
		return addmember(request,response);
	}
	
	//注册前验证邮箱是否已使用
	@RequestMapping(value="peraddcheck.htm",method=RequestMethod.POST)//请求地址
	public String peraddcheck(HttpServletRequest request,HttpServletResponse response){
		try{
			String userMail = RequestUtil.getStringParameter(request, "mail", null);
			String valResult = Member.validMail(userMail, false);
			if(valResult != null){
				return this.ajaxJsonErrorMessage(response, valResult);
			}
			boolean info = this.checkEmail(userMail);
			if (info) {
				return this.ajaxJsonSuccessMessage(response, "邮箱可用!");
			}else {
				return this.ajaxJsonErrorMessage(response, "邮箱已经使用!");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return this.ajaxJsonErrorMessage(response, "邮箱不可用使用");
		}
	}
	
	//注册时 验证用户名是否可用
	@RequestMapping(value="peraddnicknamecheck.htm",method=RequestMethod.POST)//请求地址
	public String peraddnicknamecheck(HttpServletRequest request,HttpServletResponse response){
		String userNickname = RequestUtil.getStringParameter(request, "userNickname", null);
		log.info("+++++++++++++checkName++++++++++++++ "+ userNickname);
		try{
		boolean info = checkName(userNickname);
		if (info) {
			return this.ajaxJsonSuccessMessage(response, "用户名可用!");
		}else {
			return this.ajaxJsonErrorMessage(response, "用户名不可用!");
		}
		}catch(Exception ex){
			ex.printStackTrace();
			return this.ajaxJsonErrorMessage(response, "系统忙!");
		}
	}
	
	//邮箱验证 激活信息
	@RequestMapping(value="actmember.htm",method=RequestMethod.POST)//请求地址
	public String actmember(HttpServletRequest request,Model model){
		String code = RequestUtil.getStringParameter(request, "code", null);
		String name = RequestUtil.getStringParameter(request, "username", null);
	    String type = "verification";
	    if(StringUtil.isEmpty(code)||StringUtil.isEmpty(name)){
	    	model.addAttribute("state",7);//参数错误
	    	return "actmember";
	    }
	    int state = verificationService.verficaty(type, code, name);
		model.addAttribute("state",state);
		return "actmember";
	}
	
	
	
	//提交注册
	@RequestMapping(value="regset.htm",method=RequestMethod.POST)//请求地址
	public String regset(HttpServletRequest request,HttpServletResponse response){
        
		String username = RequestUtil.getStringParameter(request, "username", null);
		String email = RequestUtil.getStringParameter(request, "email", null);
		String password = RequestUtil.getStringParameter(request, "password", null);
		String repwd = RequestUtil.getStringParameter(request, "repwd", null);
		
		HttpSession session = request.getSession(false);
		if(session == null){
			return this.ajaxJsonErrorMessage(response, "会话超时，请重新登陆");
		}
		String captchaID = session.getId();
		String challengeResponse = RequestUtil.getStringParameter(request, JCaptchaEngine.CAPTCHA_INPUT_NAME, null);
		if(challengeResponse == null)
			return this.ajaxJsonErrorMessage(response, "验证码输入有误");
		challengeResponse = challengeResponse.toUpperCase();
		try{
			if (!captchaService.validateResponseForID(captchaID, challengeResponse)) {
				return this.ajaxJsonErrorMessage(response,"验证码输入错误!");
			}
		}catch(Exception e){
			return this.ajaxJsonErrorMessage(response,"验证码输入错误!");
		}
		
		String valResult = Member.validUsername(username,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		valResult = Member.validPassword(password,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		valResult = Member.validPassword(repwd,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		
		if(!password.trim().equals(repwd.trim())){
			return this.ajaxJsonErrorMessage(response,"密码和确认密码必须相同!");
		}
		
		valResult = Member.validMail(email, false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response, valResult);
		}
		Member member = new Member();
		member.setName(username);
		member.setPassword(DigestUtils.md5Hex(password.trim()));
		member.setMail(email);
		member.setIp(request.getRemoteAddr());
		try{
			String info = memberService.toRegister(member);
			log.info(" return verfication code : " + info );
			if(info.length()>2){
				//注册成功后，首先发送激活邮件
				String path = request.getContextPath();
				String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
				basePath = basePath + "actmember.htm?code="+info+"&name="+username;
				//发送激活地址
				log.info("激活地址：" + basePath);
				String subject = "用户激活";
				MailConfig mailconfig = TemplateConfigUtil.getMailConfig(MailConfig.MAIL_SEND_ACTIVE);
				String templateFilePath = mailconfig.getTemplateFilePath();
				Map<String,Object> data = new  HashMap<String,Object>();
				data.put("title", mailconfig.getSubject());
				data.put("to", member.getName());
				data.put("time", DateUtil.dateToString(new Date(), "yyy年MM月dd日hh点mm分"));
				data.put("activeurl", basePath);
				smtpService.sendMail(subject, templateFilePath, data,member.getMail());
				return this.ajaxJsonSuccessMessage(response, "注册成功!");
			}else if(info.equals("1")){
				return this.ajaxJsonErrorMessage(response, "用户名已经存在！"); 
			}else {
				return this.ajaxJsonErrorMessage(response, "注册失败！");  
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return ajaxJsonErrorMessage(response, "系统忙!");
		}
	 
	}
	
	//验证成功后跳转地址
	@RequestMapping(value="jumper.htm",method=RequestMethod.GET)//请求地址
	public String jumper(HttpServletRequest request){
		return "jumper";
	}
	
	//登陆
	@RequestMapping(value="userlogin.htm",method=RequestMethod.POST)//请求地址
	public String ajaxlogin(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession(false);
		if(session == null){
			return this.ajaxJsonErrorMessage(response, "验证码已过期");
		}
		String challengeResponse = RequestUtil.getStringParameter(request, JCaptchaEngine.CAPTCHA_INPUT_NAME, null);
		if(StringUtil.isEmpty(challengeResponse))
			return this.ajaxJsonErrorMessage(response, "验证码输入有误");
		try{
			if (!captchaService.validateResponseForID(session.getId(), challengeResponse.toUpperCase())) {
				return this.ajaxJsonErrorMessage(response,"验证码输入错误!");
			}
		}catch(Exception e){
			return ajaxJsonErrorMessage(response,"验证码输入错误!");
		}
		String username = RequestUtil.getStringParameter(request, "username", null);
		String password = RequestUtil.getStringParameter(request, "password", null);
		String valResult = Member.validUsername(username,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		valResult = Member.validPassword(password,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		Member member = memberService.findMemberByName(username);
		if (member != null) {
			if(member.getState() != 1){
				return this.ajaxJsonErrorMessage(response,CommonData.getMemberStatuMessage(member.getState()));
			}
			if(!member.getPassword().equals(DigestUtils.md5Hex(password))){
				log.error("{"+CommonUtil.getIpAddrByRequest(request)+"}{"+username+"}登陆失败：密码错误!");
				return this.ajaxJsonErrorMessage(response,"登陆密码有误!");
			}
		} else {
			log.error("{"+CommonUtil.getIpAddrByRequest(request)+"}{"+username+"}登陆失败：用户名不存在!");
			return this.ajaxJsonErrorMessage(response,"用户名不存在!");
		}
		Map<String,Object> loginMember = new HashMap<String,Object>();
		loginMember.put(Member.LOGIN_MEMBER_ID_KEY, member.getId());
		loginMember.put(Member.LOGIN_MEMBER_NAME_KEY, member.getName());
		loginMember.put(Member.LOGIN_MEMBER_REALNAME_KEY, member.getRealname());
		loginMember.put(Member.LOGIN_MEMBER_BEAT_KEY, member.getBeat());
		loginMember.put(Member.LOGIN_MEMBER_POINTB_KEY, member.getPointb());
		loginMember.put(Member.LOGIN_MEMBER_POINTC_KEY, member.getPointc());
		session.setAttribute(LOGIN_MEMBER_SESSION_KEY, loginMember);
		return this.ajaxJsonSuccessMessage(response,null);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="getlogininfo.htm",method=RequestMethod.GET)//
	public String getlogininfo(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Map jsonMap = new HashMap();
		if(loginMember == null){
			jsonMap.put("memberIsLogin", "0");
			return this.ajaxJson(response, jsonMap);
		}
		jsonMap.put("memberIsLogin", "1");
		jsonMap.put(Member.LOGIN_MEMBER_ID_KEY, loginMember.get(Member.LOGIN_MEMBER_ID_KEY));
		jsonMap.put(Member.LOGIN_MEMBER_NAME_KEY, loginMember.get(Member.LOGIN_MEMBER_NAME_KEY));
		jsonMap.put(Member.LOGIN_MEMBER_REALNAME_KEY, loginMember.get(Member.LOGIN_MEMBER_REALNAME_KEY));
		jsonMap.put(Member.LOGIN_MEMBER_BEAT_KEY, loginMember.get(Member.LOGIN_MEMBER_BEAT_KEY));
		jsonMap.put(Member.LOGIN_MEMBER_POINTB_KEY, loginMember.get(Member.LOGIN_MEMBER_POINTB_KEY));
		jsonMap.put(Member.LOGIN_MEMBER_POINTC_KEY, loginMember.get(Member.LOGIN_MEMBER_POINTC_KEY));
		return this.ajaxJson(response, jsonMap);
	}
	
	//检测登陆
	@RequestMapping(value="inimember.htm",method=RequestMethod.GET)//请求地址
	public String inimember(HttpServletRequest request,Model model){
		Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
		String username = (String)loginMember.get(Member.LOGIN_MEMBER_NAME_KEY);
		if(uid == null){
			return "index";
		}else{
			int state = 0;
			int c = letterService.getLetterCount(username, state);
			model.addAttribute("count", c);
		}
		
		return "inimember";
	}
	
	//退出
	@RequestMapping(value="logout.htm",method=RequestMethod.GET)//请求地址
	public String logout(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession(false);
		if(session != null)
			session.removeAttribute(LOGIN_MEMBER_SESSION_KEY);
		return "redirect:/index.htm";
	}
	
	//找回密码页面
	@RequestMapping(value="getpwd.htm",method=RequestMethod.GET)//请求地址
	public String getpwd(HttpServletRequest request,HttpServletResponse response){
		return "getpwd";
	}
	
	//找回密码处理方法
	public String getpwdhan(HttpServletRequest request,HttpServletResponse response){
		String mailbox = RequestUtil.getStringParameter(request, "mailbox", null);
		String forgetcode = RequestUtil.getStringParameter(request, "forgetcode", null);
		
		if (checkVerify(request,forgetcode)){
			if (isMember(request,response).equals("ok")){
				//$verification = D('Verification');
				//$smtp = A('Smtp');
				int count = verificationService.getpwd(mailbox, "getpwd", forgetcode) ;
				if (count == 0){
					String header = "找回密码操作确认";
				     //选择模板
	                Map<String,Object> data = new HashMap<String,Object>();
					boolean info = smtpService.sendMail(header, "templateFilePath", data, mailbox);
					if (info){
						return this.ajaxJsonSuccessMessage(response, "发送成功!");
					}else{
						return this.ajaxJsonErrorMessage(response, "发送失败!");
					}
				}else {
					return this.ajaxJsonErrorMessage(response, "找回密码失败！");
				}
			}else {
				return this.ajaxJsonErrorMessage(response, "邮箱不存在！");
			}
		}else {
			return this.ajaxJsonErrorMessage(response, "验证码错误！");
		}
	}
	
	//重设密码结果
	@RequestMapping(value="setpwd.htm",method=RequestMethod.GET)//请求地址
	public String setpwd(HttpServletRequest request,Model model){
		String code = RequestUtil.getStringParameter(request, "code", null);
		String type = "getpwd";
		String randpwd = StringUtil.getRandomStr8();
		String password = DigestUtils.md5Hex(randpwd);
		int c = verificationService.repaySetpwd(code, type, password);
        if(c==0){
        	model.addAttribute("pwd", randpwd);
        }
		return "setpwd";
	}
	
	//获取统计信息
	 @RequestMapping(value="getcount.htm",method=RequestMethod.GET)//请求地址
	public String getcount(HttpServletRequest request,HttpServletResponse response){
		 Member member =null;
		 Map<String,String> jsonMap = new HashMap<String,String>();
		 if(islogin(request)){
			 Map<String,Object> loginMember = getLoginMember(request.getSession(false));
			Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
			member =  memberService.findMemberById(uid);
			 jsonMap.put("beat", String.valueOf(member.getBeat()));
			 jsonMap.put("pointb", String.valueOf(member.getPointb()));
			 jsonMap.put("pointc", String.valueOf(member.getPointc()));
		 }else{
			 jsonMap.put("beat", "0");
			 jsonMap.put("pointb", "0");
			 jsonMap.put("pointc", "0");
		 }

		 return this.ajaxJson(response, jsonMap);
	}
	
	 
	 @RequestMapping(value="ajaxcheckuser.htm",method=RequestMethod.GET)//请求地址
	public String ajaxcheckuser(HttpServletRequest request,HttpServletResponse response){
		boolean state = updatestate(request);
		if (state) {
			return this.ajaxJsonSuccessMessage(response, "正常");
		}else {
			return this.ajaxJsonErrorMessage(response, "错误");
		}

	}
	
	//单独晒图
	 @RequestMapping(value="detail.htm",method=RequestMethod.GET)//请求地址
	public String detail(HttpServletRequest request,Model model){
		long id = RequestUtil.getLongParameter(request, "id", 0);
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		Page page = new Page(pageno, 10);
		int state = 1; 
		Sunpic sunpic  = sunpicService.sunpics(state, id);
		if(sunpic!=null){			
			List<Object> participatedata = participateService.getParticipateAuction(page, sunpic.getUid(), 10);
			model.addAttribute("participatedata", participatedata);
			model.addAttribute("sunpic", sunpic);
		}
		return "detail";
	}
	
	//个人中心
	//登陆
	@RequestMapping(value="center.htm",method=RequestMethod.GET)//请求地址
	public String center(HttpServletRequest request,Model model){
		int uid = RequestUtil.getIntParameter(request, "id", 0);
		if(uid!=0){
			int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
			Page page = new Page(pageno, 10);
			int limit = 10;
			int state = 1;
			List<Object> sunpics = sunpicService.sunpics(state, uid, limit);
			Member meber = memberService.findMemberById(uid);
			List<Object> participatedata = participateService.getParticipateAuction(page, uid, limit);
		    model.addAttribute("participatedata", participatedata);
		    model.addAttribute("sunpics", sunpics);
		    model.addAttribute("meber", meber);
		}
		return "center";
		
	}
 
	
	//是否登陆 返回数据库中数据
	public boolean islogin(HttpServletRequest request){
		Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
		if(uid == null){
			return false;
		}else{
			Object oj = memberService.islogin(uid);
			if(oj==null){
				return false;
			}else{
				return true;
			}
		}
		
	}
	
	
	//更新状态
	public boolean updatestate(HttpServletRequest request){
		Object obj = islogin(request);
		if(obj == null){
			return false;
		}
		Member user = (Member)obj;
	    //$_SESSION['user'] = $userdata;
		Object ispun = punchService.isPunch(user.getId());
		if (ispun!=null){
			//cookie('isgetPointB',1); //已经打卡
			return false;
		}else {
			//cookie('isgetPointB',0); //为打卡
			return true;
		}
	}
	
	//是否是会员邮箱
	public String isMember(HttpServletRequest request,HttpServletResponse response){
		String email = RequestUtil.getStringParameter(request, "email", null);
		String valResult = Member.validUsername(email,false);
		if(valResult != null){
			return this.ajaxJsonErrorMessage(response,valResult);
		}
		Object obj = memberService.checkEmail(email);
		if(obj!=null){
			return this.ajaxJsonErrorMessage(response,"邮箱已经被使用!");
		}else{
			return this.ajaxJsonSuccessMessage(response, "ok");
		}
	}
	
	//验证登陆
	public boolean checkLogin(HttpServletRequest request, String mail,String password){
	    Object obj = memberService.checkLogin(mail, password);
	    Member user = (Member)obj;
	    if(user==null){
	    	return false;
	    }else{
	    	Loginlog loginlog = new Loginlog();
	    	loginlog.setAddress(request.getRemoteHost());
	    	loginlog.setIp(request.getRemoteAddr());
	    	loginlog.setUid(user.getId());
	    	loginlog.setName(user.getName());
	    	memberService.loginlog(loginlog);
	    	HttpSession session = request.getSession(false);
			//TODO 设置session
			return true;
	    }
	}
	
	//验证邮箱
	protected boolean checkEmail(String email){
		String objemail = (String)memberService.checkEmail(email);
		log.info(" +++++++++++++++ checkEmail +++++++++++ " + objemail);
		if(objemail == null){
			return true;
		}
		if(objemail.equals(email)){
			return false;
		}else{
			return true;
		}
	}
	
	//验证昵称
	protected boolean checkName(String name){
		if(StringUtil.isEmpty(name)) {
			return false;
		}else {
			boolean id =  memberService.checkName(name);
			if(!id){
				return true;
			}else{
				return false;
			}
		}
	}
	
	//验证验证码
	protected boolean checkVerify(HttpServletRequest request,String verify){
		if (StringUtil.isEmpty(verify)){
			return false;
		}else {
			String sverify = (String)this.getSession(request).getAttribute("verify");
			if (DigestUtils.md5Hex(verify).equals(sverify)){
				return false;
			}else {
				return true;
			}
		}
	}
	
	//推荐好友
    public String copy_code(HttpServletRequest request)
    {
    	Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
    	request.setAttribute("id", uid);
    	return "copy_code";
    }
	
    
	//列出头像
	public String memberlogo(HttpServletRequest request){
		List<Map<String,Object>> logos = memberService.memberlogo();
		Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
		if(uid != null){
			request.setAttribute("uid", uid);
			request.setAttribute("logs", logos);
		}
		return "memberlog";
	}
	
	
}
